const { responsSuccess, responsError } = require("../utils/responseUtil");
const { getValueByKey } = require("../utils/utils");
const {
  getRepoListByTeamID,
  getAllRepoListWithBranch,
  addRepoInfo,
  deleteRepoByrid,
  modifyRepoInfo,
  searchRepoInfoByKeyword,
  getRepoListByBranchId,
} = require("../model/repos");
const { getAllGroupList } = require("../model/teams");
const { validateParams } = require("../utils/validateReqParam");
const { ParamVerifyBusinessError } = require("../commonError/ParamError");
const { scriptIsRunningError } = require("../commonError/logicError");
const syncRepos = require("../script/syncRepos");
const syncRepo = require("../script/syncRepos");
const { output } = require("../config/config");

module.exports.getRepoListByTeamIDController = function (request, response) {
  validateParams(request.params, {
    //url参数即使传递数字，接收到也是string类型
    teamId: { required: true, type: "string", default: null, strReg: /^\d+$/ },
  })
    .then((reqData) => {
      const teamId = reqData["teamId"];
      getRepoListByTeamID(teamId)
        .then((repos) => {
          responsSuccess(response, { repos });
        })
        .catch((err) => {
          console.log("getRepoListByTeamIDController --> err", err);
          responsError(response, err);
        });
    })
    .catch((err) => {
      console.log("getRepoListByTeamIDController --> err", err);
      responsError(response, err);
    });
};

module.exports.getAllRepoListController = async function (request, response) {
  validateParams(request.body, {
    pageNum: { required: false, type: "number", default: null },
    pageSize: { required: false, type: "number", default: null },
  })
    .then((reqData) => {
      getAllRepoListWithBranch(reqData)
        .then((repoRes) => {
          responsSuccess(response, repoRes);
        })
        .catch((err) => {
          console.log("getAllRepoListController --> err", err);
          responsError(response, err);
        });
    })
    .catch((err) => {
      console.log("getAllRepoListController --> err", err);
      responsError(response, err);
    });
};

module.exports.addRepoInfoController = function (request, response) {
  validateParams(
    request.body,
    {
      rid: { required: false, type: "number", default: null },
      groupId: { required: true, type: "number", default: null },
      gitlabName: { required: true, type: "string", default: null },
      gitlabCloneUrl: { required: true, type: "string", default: null },
    },
    async (reqData) => {
      let teamList = await getAllGroupList();
      if (getValueByKey(reqData.groupId, "id", teamList).length === 0) {
        throw new ParamVerifyBusinessError("不存在该组id");
      }
      return reqData;
    }
  )
    .then((reqData) => {
      if (reqData.rid == null) {
        //新增
        addRepoInfo(reqData)
          .then(() => {
            responsSuccess(response, null);
          })
          .catch((err) => {
            console.log("addRepoInfoController --> err", err);
            responsError(response, err);
          });
      } else {
        //修改
        modifyRepoInfo(reqData)
          .then(() => {
            responsSuccess(response, null);
          })
          .catch((err) => {
            console.log("addRepoInfoController --> err", err);
            responsError(response, err);
          });
      }
    })
    .catch((err) => {
      console.log("addRepoInfoController --> err", err);
      responsError(response, err);
    });
};

module.exports.deteleRepoInfoByRIDController = function (request, response) {
  validateParams(request.body, {
    rid: { required: true, type: "number", default: null },
  })
    .then((reqData) => {
      deleteRepoByrid(reqData.rid)
        .then(() => {
          responsSuccess(response, null);
        })
        .catch((err) => {
          console.log("deteleRepoInfoByRIDController --> err", err);
          responsError(response, err);
        });
    })
    .catch((err) => {
      console.log("deteleRepoInfoByRIDController --> err", err);
      responsError(response, err);
    });
};

module.exports.searchRepoInfoByKeywordController = function (
  request,
  response
) {
  validateParams(request.body, {
    pageNum: { required: false, type: "number", default: null },
    pageSize: { required: false, type: "number", default: null },
    searchStr: { required: true, type: "string", default: null },
  })
    .then((reqData) => {
      searchRepoInfoByKeyword(reqData)
        .then((res) => {
          responsSuccess(response, res);
        })
        .catch((err) => {
          console.log("searchRepoInfoByKeywordController --> err", err);
          responsError(response, err);
        });
    })
    .catch((err) => {
      console.log("searchRepoInfoByKeywordController --> err", err);
      responsError(response, err);
    });
};

let syncReposLock = false; //锁
module.exports.syncReposController = async function (request, response) {
  if (syncReposLock === false) {
    try {
      syncReposLock = true;

      let reposList = await getRepoListByBranchId({
        branchId: 1,
      });

      responsSuccess(response, "数据同步中");
      await syncRepo(reposList, output);

      syncReposLock = false;
    } catch (err) {
      responsError(response, err);
      syncReposLock = false;
    }
    return;
  }
  responsError(response, new scriptIsRunningError());
};
